package com.googlecode.lookie.logview.internal;

import java.util.Enumeration;

import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.richclient.application.support.AbstractView;
import org.springframework.richclient.table.TableUtils;
import org.springframework.richclient.table.renderer.BeanTableCellRenderer;

import com.googlecode.lookie.core.log.Log;
import com.googlecode.lookie.core.log.LogListener;
import com.googlecode.lookie.core.log.LogRecord;
import com.googlecode.lookie.core.log.LogStore;
import com.googlecode.lookie.core.log.LogStoreListener;

public class LogView
    extends AbstractView
    implements LogStoreListener, LogListener
{

    private static final Logger logger = LoggerFactory.getLogger( LogView.class );

    private LogTableModel tableModel;

    private JTable table;

    @Override
    protected JComponent createControl()
    {
        table = TableUtils.createStandardSortableTable( tableModel = new LogTableModel() );

        BeanTableCellRenderer cellRenderer = new BeanTableCellRenderer();
        for ( Enumeration<TableColumn> en = table.getColumnModel().getColumns(); en.hasMoreElements(); )
        {
            TableColumn column = en.nextElement();
            column.setCellRenderer( cellRenderer );
        }

        getLog().addLogListener( this );

        return getComponentFactory().createScrollPane( table );
    }

    private Log getLog()
    {
        return (Log) getApplicationServices().getService( Log.class );
    }

    public void logging( LogRecord record, Log log )
    {
        tableModel.addRow( record );
    }

    public void changed( LogStore store, ChangeType type )
    {
        logger.info( store.toString() );
    }

    @Override
    public void dispose()
    {
        getLog().removeLogListener( this );
        super.dispose();
    }

}
